<?php

namespace app\common\logic;

use app\common\model;
use think\Validate;

class GoodsLogic
{
    /**
     * Undocumented function
     *
     * @param int $goodsId
     * @param string $type
     * @param int $changes
     * @return array
     */
    public function savelsit($goodsId, $type, &$changes = 0)
    {
        $postModels = [];
        if ($type == 'spec_list') {
            $postModels = input('post.spec_list/a', []);

        } else {
            $postModels = input('post.attr_list/a', []);
        }

        $errors = [];
        $names = [];

        $valedate = Validate::make([
            'name|名称' => 'require',
            'value|值' => 'require',
        ]);

        foreach ($postModels as $key => &$pdata) {

            $dataModel = $type == 'spec_list' ? new model\ShopGoodsSpec() : new model\ShopGoodsAttr();

            $result = $valedate->check($pdata);

            if (true !== $result) {
                $errors[] = '规格/属性[' . $pdata['name'] . ']' . $result;
                continue;
            }

            $values = array_filter(array_filter(explode(',', $pdata['value']), 'strlen'), 'trim');
            $pdata['value'] = implode(',', $values);
            $pdata['goods_id'] = $goodsId;

            $is_del = isset($pdata['__del__']) && $pdata['__del__'] == 1;
            $is_add = strpos($key, '__new__') !== false;

            if (!$is_del && in_array($pdata['name'], $names)) {
                $errors[] = '规格/属性[' . $pdata['name'] . ']重复，请修改';
                if ($is_add) {
                    continue;
                }
            }

            if ($is_add) {
                $res = $dataModel->isUpdate(false)->save($pdata);
                if ($res) {
                    $names[] = $pdata['name'];
                    if ($type == 'spec_list') {
                        $this->saveSpecValues($dataModel['id'], $goodsId, $values);
                    }
                    $changes += 1;
                } else {
                    $errors[] = '规格/属性[' . $pdata['name'] . ']保存出错';
                }
            } else {
                if ($is_del) {
                    $res = $dataModel::destroy($key);
                    if ($res) {
                        $changes += 1;
                        if ($type == 'spec_list') {
                            model\ShopGoodsSpecValue::where(['spec_id' => $key])->delete(); //删除规格对应值
                        }
                    }
                } else {
                    $exist = $dataModel->get($key);
                    if ($exist && $exist['goods_id'] == $pdata['goods_id'] && $exist['value'] == $pdata['value'] && $exist['name'] == $pdata['name']) {
                        continue;
                    }
                    $res = $dataModel->isUpdate(true, ['id' => $key])->save($pdata);
                    if ($res) {
                        $names[] = $pdata['name'];
                        if ($type == 'spec_list') {
                            $this->saveSpecValues($key, $goodsId, $values);
                        }
                        $changes += 1;
                    } else {
                        $errors[] = '规格/属性[' . $pdata['name'] . ']保存出错';
                    }
                }
            }
        }

        if (model\ShopGoodsSpec::where(['goods_id' => $goodsId])->count() == 0) {
            model\ShopGoodsSpecValue::where(['goods_id' => $goodsId])->delete();
            model\ShopGoodsSpecPrice::where(['goods_id' => $goodsId])->delete();
        }

        return $errors;
    }

    /**
     * Undocumented function
     *
     * @param int $goodsId
     * @return array
     */
    public function savePrices($goodsId)
    {
        $priceList = input('post.price_list/a', []);

        $specModel = new model\ShopGoodsSpec();
        $specValueModel = new model\ShopGoodsSpecValue();

        $sids = $specModel->where(['goods_id' => $goodsId])->order('sort')->column('id');

        if (empty($sids)) {
            return [];
        }

        $valedate = Validate::make([
            'sale_price|销售价格' => 'require|float',
            'stock|库存' => 'require|integer',
        ]);

        $mvals = [];

        $specIds = '_' . implode('_', $sids) . '_';
        $specKeyIds = [];

        $errors = [];

        foreach ($priceList as $key => &$pdata) {

            $goodsPriceModel = new model\ShopGoodsSpecPrice;

            $result = $valedate->check($pdata);

            if (true !== $result) {
                $errors[] = '规格/属性有误：' . $result;
                continue;
            }

            $is_del = isset($pdata['__del__']) && $pdata['__del__'] == 1;
            $is_add = strpos($key, '__new__') !== false;

            $mvals = [];
            $modelNames = [];

            $data = [];

            foreach ($sids as $sid) {
                $selected = isset($pdata['spec_id' . $sid]) ? $pdata['spec_id' . $sid] : '0';
                $mvals[] = $selected;
                $data[$sid] = $selected;

                $valueInfo = $specValueModel->get($selected);
                $modelNames[] = $valueInfo ? str_replace('*', '＊', $valueInfo['value']) : '-'; //规格名称里面的*号替换一下，避免混淆
            }

            if (empty($mvals)) {
                if (!$is_add) {
                    $goodsPriceModel->destroy($key);
                }
                continue;
            }

            sort($mvals); //排序，前台传过来的也要排序，一样的话就能匹配。1,2.3 | 2,3,1 | 3,1,2 其实是一样的

            $pdata['spec_key'] = '_' . implode('_', $mvals) . '_';
            $pdata['data'] = json_encode($data);
            $pdata['spec_key_name'] = implode('*', $modelNames);
            $pdata['goods_id'] = $goodsId;
            $pdata['spec_ids'] = $specIds;

            if (!$is_del && in_array($pdata['spec_key'], $specKeyIds)) {
                $errors[] = '价格/库存组合[' . $pdata['spec_key_name'] . ']重复';
                if ($is_add) {
                    continue;
                }
                if (empty($pdata['sku'])) {
                    $pdata['sku'] = '-';
                }
            }

            if ($is_add) {
                $res = $goodsPriceModel->save($pdata);
                if ($res) {
                    $specKeyIds[] = $pdata['spec_key'];
                } else {
                    $errors[] = '价格/库存[' . $pdata['spec_key_name'] . ']保存出错';
                }
            } else {
                if ($is_del) {
                    $goodsPriceModel->destroy($key);
                } else {
                    $res = $goodsPriceModel->save($pdata, ['id' => $key]);
                    if ($res) {
                        $specKeyIds[] = $pdata['spec_key'];
                    } else {
                        $errors[] = '价格/库存[' . $pdata['spec_key_name'] . ']保存出错';
                    }
                }
            }
        }

        return $errors;
    }

    /**
     * Undocumented function
     *
     * @param int $model_id
     * @param array $values
     * @return void
     */
    public function saveSpecValues($spec_id, $goods_id, $values)
    {
        if (empty($spec_id) || empty($goods_id)) {
            return;
        }

        $specValueModel = new model\ShopGoodsSpecValue();

        $allIds = $specValueModel->where(['spec_id' => $spec_id])->column('id');

        $inUseIds = [];
        foreach ($values as $v) {
            $mv = $specValueModel->where(['spec_id' => $spec_id, 'value' => $v])->find();
            if (!$mv) {
                $specValueModel->create([
                    'spec_id' => $spec_id,
                    'value' => $v,
                    'goods_id' => $goods_id,
                ]);
            } else {
                $inUseIds[] = $mv['id'];
            }
        }

        $notInUseIds = array_diff($allIds, $inUseIds);

        if (!empty($notInUseIds)) {
            $specValueModel->destroy(array_values($notInUseIds));
        }
    }

    public function getSpecList($q = '')
    {
        $where = [];

        if ($q) {
            $where[] = ['name|spu', 'like', '%' . $q . '%'];
        }

        $goodsModel = new model\ShopGoods();
        $specPriceModel = new model\ShopGoodsSpecPrice();

        $specList = [];
        $goodsList = $goodsModel->where($where)->select();
        $priceList = [];

        foreach ($goodsList as $goods) {
            $priceList = $specPriceModel->where(['goods_id' => $goods['id']])->select();

            if (count($priceList)) { //有多种规格
                foreach ($priceList as $price) {
                    $specList[] = [
                        'id' => $price['spec_key'],
                        'text' => $goods['name'] . '#' . $price['sku'] . '[' . $price['spec_key_name'] . ']￥' . $price['sale_price'] . '库存:' . $price['stock'],
                    ];
                }
            } else { //无多种规格
                $specList[] = [
                    'id' => 'g_' . $goods['id'],
                    'text' => $goods['name'] . '#' . $goods['spu'] . '[*无规格*]￥' . $goods['sale_price'] . '库存:' . $goods['stock'],
                ];
            }
        }

        return $specList;
    }

    /**
     * 数据转换
     * @param $data
     * @return mixed
     */
    function dataConversion($data)
    {
        // 没有轮播图，使用主图替换
        if (!$data["images"]) {
            $data["imagesList"] = $data["logo"];
        } else {
            $data['imagesList'] = stringToArray($data['images']);
        }
        // 视频
        $data['video'] = replace_url($data['video']);
        // 详情
        $data['content'] = replace_src_url($data['content']);
        // 品牌
        $data['brand'] = model\ShopBrand::where('id', $data['brand_id'])->find();

        // 规格
        $data = $this->getGoodsSpec($data);

        //指定商品
        $data['goods_ids'] = stringToArray($data['for_goods']);

        //资质
        $data['certs_ids'] = stringToArray($data['for_certs']);

        // 是否参与营销活动
        $marketing = model\Marketing::where('done', 1)->where('goods_id', $data['id'])->select();
        foreach ($marketing as &$item) {
            $item['img'] = replace_url($item['img']);
        }
        $data['marketing'] = $marketing;

        return $data;
    }

    /**
     * 组装商品规格
     * @param $goods
     * @param $delivery_type
     * @param $is_free_queuing
     * @return mixed
     */
    function getGoodsSpec($goods, $delivery_type = 0, $is_free_queuing = 0)
    {
        $specList = model\ShopGoodsSpec::where(['goods_id' => $goods['id']])->select();
        $specPirce = model\ShopGoodsSpecPrice::where(['goods_id' => $goods['id']])->select();

        $spec_info_list = [];
        $goods_spec = [];

        if (count($specList) > 0) { //有多种规格
            foreach ($specList as $spec) {
                $spec_list = model\ShopGoodsSpecValue::where(['goods_id' => $goods['id'], 'spec_id' => $spec['id']])->select();
                $value = [];
                foreach ($spec_list as $li) {
                    $value[] = [
                        'spec_name' => $spec['name'],
                        'spec_value_name' => $li['value'],
                        'spec_id' => $spec['id'],
                        'spec_value_id' => $li['id'],
                    ];
                }
                $spec_info_list[] = [
                    'spec_name' => $spec['name'],
                    'spec_id' => $spec['id'],
                    'value' => $value,
                ];
            }

            foreach ($specPirce as $i => $sku) {
                /*if ($member_price) {
                    // 规格价 - 会员的优惠价
                    $sku["sale_price"] = $sku["sale_price"] - $member_price;
                }*/

                if (in_array($goods['category_id'], [9, 10, 11, 12, 13, 14, 15, 16, 17])) {
                    $sale_price = $this->getSalePrice($goods, $sku, $delivery_type, $is_free_queuing);
                } else {
                    $sale_price = $sku['sale_price'];
                }

                $goods_spec[] = [
                    'id' => $sku['id'],
                    'thumb' => $goods['logo'],
                    'specs' => trim($sku['spec_key'], '_'),
                    'stock' => $sku['stock'],
                    'price' => $sale_price,
                    'title' => $sku['spec_key_name'],
                ];

                if ($i === 0) {
                    $goods['sale_price'] = $sale_price;
                    $goods['premium_price'] = $sku['premium_price'];
                }
            }
        } else { //无多种规格
            $spec_info_list[] = [
                'spec_name' => '规格',
                'spec_id' => 'none',
                'value' => [[
                    'spec_name' => '规格',
                    'spec_value_name' => '默认',
                    'spec_id' => 'none',
                    'spec_value_id' => 'none',
                ]],
            ];

            if (in_array($goods['category_id'], [9, 10, 11, 12, 13, 14, 15, 16, 17])) {
                $sale_price = $this->getSalePrice($goods, '', $delivery_type, $is_free_queuing);
                $goods['sale_price'] = $sale_price;
            } else {
                $sale_price = $goods['sale_price'];
            }

            $goods_spec[] = [
                'id' => 'none',
                'thumb' => $goods['logo'],
                'specs' => 'none',
                'stock' => $goods['stock'],
                'price' => $sale_price,
                'title' => '默认',
            ];
        }

        $goods['spec_info_list'] = $spec_info_list;
        $goods['goods_spec'] = $goods_spec;

        return $goods;
    }

    /**
     * 获取销售价格
     * @param $goods [商品信息]
     * @param $sku [商品规格]
     * @param $delivery_type [配送方式]
     * @param $is_free_queuing [是否排队免单]
     * @return mixed|string
     */
    function getSalePrice($goods, $sku, $delivery_type, $is_free_queuing)
    {
        $sale_price = 0;
        if ($sku) {
            //设置了多规格
            if ($delivery_type == 1) {
                // 自提
                if ($is_free_queuing == 1) {
                    // 不含配送排队免单价
                    $sale_price = round($sku['free_queuing_price'] + $sku['premium_price'], 2);
//                    makelog($goods['id'] . "#" . $goods['name'] . "#" . $goods['store_id'] . "有规格不含配送排队免单价-1：" . $sale_price, 'order/create');
                } else {
                    // 不含配送销售价
                    $sale_price = round($sku['sale_price'] + $sku['premium_price'], 2);
//                    makelog($goods['id'] . "#" . $goods['name'] . "#" . $goods['store_id'] . "有规格不含配送销售价-1：" . $sale_price, 'order/create');
                }
            } else {
                // 配送
                if ($is_free_queuing == 1) {
                    // 含配送排队免单价
                    $sale_price = round($sku['free_queuing_price'] + $goods['delivery_price'] + $sku['premium_price'], 2);
//                    makelog($goods['id'] . "#" . $goods['name'] . "#" . $goods['store_id'] . "有规格含配送排队免单价-1：" . $sale_price, 'order/create');
                } else {
                    // 含配送销售价
                    $sale_price = round($sku['sale_price'] + $goods['delivery_price'] + $sku['premium_price'], 2);
//                    makelog($goods['id'] . "#" . $goods['name'] . "#" . $goods['store_id'] . "有规格含配送销售价-1：" . $sale_price, 'order/create');
                }
            }
        } else {
            //没有设置多规格
            if ($delivery_type == 1) {
                // 自提
                if ($is_free_queuing == 1) {
                    // 不含配送排队免单价
                    $sale_price = round($goods['free_queuing_price'] + $goods['premium_price']);
//                    makelog($goods['id'] . "#" . $goods['name'] . "#" . $goods['store_id'] . "无规格不含配送排队免单价-1：" . $sale_price, 'order/create');
                } else {
                    // 不含配送销售价
                    $sale_price = round($goods['sale_price'] + $goods['premium_price']);
//                    makelog($goods['id'] . "#" . $goods['name'] . "#" . $goods['store_id'] . "无规格不含配送销售价-1：" . $sale_price, 'order/create');
                }
            } else {
                // 配送
                if ($is_free_queuing == 1) {
                    // 含配送排队免单价
                    $sale_price = round($goods['free_queuing_price'], $goods['delivery_price'] + $goods['premium_price'], 2);
//                    makelog($goods['id'] . "#" . $goods['name'] . "#" . $goods['store_id'] . "无规格含配送排队免单价-1：" . $sale_price, 'order/create');
                } else {
                    // 含配送销售价
                    $sale_price = round($goods['sale_price'], $goods['delivery_price'] + $goods['premium_price'], 2);
//                    makelog($goods['id'] . "#" . $goods['name'] . "#" . $goods['store_id'] . "无规格含配送销售价-1：" . $sale_price, 'order/create');
                }
            }
        }

        return $sale_price;
    }

    /**
     * 根据商品分类获取商品类型
     * @param $category_id
     * @return int
     */
    function getGoodsType($category_id)
    {
        $goods_type = 0;//商品类型，0普通商品，1积分商品，2酒店，3门票，4水票，5饮水设备，6水产品，7虚拟商品
        if ($category_id == 4) {
            $goods_type = 2;
        }
        if ($category_id == 6) {
            $goods_type = 7;
        }
        if ($category_id == 7) {
            $goods_type = 3;
        }
        if ($category_id == 10 || $category_id == 11) {
            $goods_type = 6;
        }
        if ($category_id == 12) {
            $goods_type = 4;
        }
        if ($category_id == 14 || $category_id == 15 || $category_id == 16 || $category_id == 17) {
            $goods_type = 5;
        }

        return $goods_type;
    }
}
